<?php

namespace Apps\AppApi\Method\Common;


use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\MobileSMS;
use Apps\Common\Models\UserBase;
use PhalconPlus\Api\Common\ResultStatus;

class SmsSend extends BaseMethod
{
    public function run()
    {
        $type = $this->getDataItem('type', null);
        $number = $this->getDataItem('number', null);
        if(empty($type) || empty($number) || !preg_match("/^1\d{10}/", $number)) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '');
        }
        // 验证手机号码是否存在
        if(in_array($type, ['register', 'update_password', 'update_mobile'])) {
            $exist = UserBase::query()
                ->where('user_account = :m:', ['m' => $number])
                ->execute()
                ->getFirst();
            if($type == 'register' && $exist == true) {
                $this->setResult([
                    'id' => 0,
                   // 'success' => 0,
                    'success' => 2,
                    'errmsg' => '手机号码已经注册过了！',
                ]);
                return false;
            }
            if($type == 'update_password' && $exist  == false) {
                $this->setResult([
                    'id' => 0,
                    //'success' => 0,
                    'success' => 3,
                    'errmsg' => '手机号码还未注册！',
                ]);
                return false;
            }
        }
        $id = MobileSMS::Send($type, $number, $this->apiAccessToken->id);

        if($id === false)
        {
            $this->setResult([
                'id' => 0,
                'success' => 0,
                'errmsg' => '发送失败，请重试！',
            ]);
        } else {
            $this->setResult([
                'id' => $id,
                'success' => 1,
                'errmsg' => '',
            ]);
        }
    }
}